package xin.printk.android.data.db.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import xin.printk.android.BasicApplication;
import xin.printk.android.data.db.DatabaseHelper;
import xin.printk.android.data.db.SQL;
import xin.printk.android.data.entity.User;

public class UserDao {

    public static long register(String account, String password) {
        SQLiteOpenHelper helper = new DatabaseHelper(BasicApplication.getContext());
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("account ", account);
        values.put("password", password);
        values.put("username", account);
        return db.insert(SQL.TABLE_USER, null, values);
    }

    public static User login(String account, String password) {
        SQLiteOpenHelper helper = new DatabaseHelper(BasicApplication.getContext());
        SQLiteDatabase db = helper.getReadableDatabase();
        String sql = "select * from " + SQL.TABLE_USER + " where account = ? and password = ?";
        Cursor cursor = db.rawQuery(sql, new String[]{account, password});
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                User user = User.getInstance();
                user.setAccount(cursor.getString(cursor.getColumnIndex("account")));
                user.setPassword(cursor.getString(cursor.getColumnIndex("password")));
                user.setUsername(cursor.getString(cursor.getColumnIndex("username")));
                user.setPhone(cursor.getString(cursor.getColumnIndex("telephone")));
                user.setTelephone(cursor.getString(cursor.getColumnIndex("password")));
                user.setIntroduction(cursor.getString(cursor.getColumnIndex("introduction")));
                user.setCompany(cursor.getString(cursor.getColumnIndex("company")));
                user.setJob(cursor.getString(cursor.getColumnIndex("job")));
                user.setAddress(cursor.getString(cursor.getColumnIndex("address")));
                user.setOnline(true);
                return user;
            }
            cursor.close();
        }
        return null;
    }

}
